package com.voicechat.firstmet.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CirclePictureAdapter;
import com.voicechat.firstmet.adapter.FullyGridLayoutManager;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.fragment.EmojiShowFragment;
import com.voicechat.firstmet.fragment.SendPostVoiceFragment;
import com.voicechat.firstmet.imcontrol.FileUtil;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.AudioRecorderUtil;
import com.voicechat.firstmet.utils.CheckAudioPermission;
import com.voicechat.firstmet.utils.DataCleanManager;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import library.mentions.edit.MentionEditText;

/**
 * 发送帖子页面
 */
public class SendPostActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_post_send)
    TextView tvPostSend;
    @BindView(R.id.et_post_title)
    EditText etPostTitle;
    @BindView(R.id.et_post_content)
    MentionEditText etPostContent;
    @BindView(R.id.recycler_send_pictuer)
    RecyclerView recyclerSendPictuer;
    @BindView(R.id.linear_send_post_picture)
    LinearLayout linearSendPostPicture;
    @BindView(R.id.linear_send_post_emjoy)
    LinearLayout linearSendPostEmjoy;
    @BindView(R.id.linear_send_post_aite)
    LinearLayout linearSendPostAite;
    @BindView(R.id.fl_emogi)
    FrameLayout flEmogi;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.image_enjoy)
    ImageView imageEnjoy;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.ll_emogi)
    LinearLayout llEmogi;
    @BindView(R.id.iv_emogi)
    ImageView ivEmogi;
    @BindView(R.id.linear_2)
    LinearLayout linear2;
    @BindView(R.id.radio_vip_renew)
    CheckBox radioVipRenew;
    @BindView(R.id.radio_group)
    RelativeLayout radioGroup;
    @BindView(R.id.linear_edittext)
    LinearLayout linearEdittext;
    @BindView(R.id.image_send_voice_icon)
    ImageView imageSendVoiceIcon;
    @BindView(R.id.tv_voice_time)
    TextView tvVoiceTime;
    @BindView(R.id.linear_send_voice)
    RelativeLayout linearSendVoice;
    @BindView(R.id.image_voice)
    ImageView imageVoice;
    @BindView(R.id.linear_send_post_voice)
    LinearLayout linearSendPostVoice;
    @BindView(R.id.fl_voice)
    FrameLayout flVoice;
    private String TAG = "SendPostActivity";
    //选择图片list
    private List<LocalMedia> tlist;
    private List<LocalMedia> selectList;
    private CirclePictureAdapter circlePictureAdapter;
    private EmojiShowFragment emojiShowFragment;

    private boolean keyboardShown;
    private boolean isEmogiShow;
    private int supportSoftInputHeight;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private SendPostVoiceFragment sendVoiceFragment;
    private String showFragmentTag;
    /*private RecorderUtil recorder = new RecorderUtil();*/
    private AudioRecorderUtil recorder;
    private MediaUtil mediaUtil;
    private AnimationDrawable frameAnimatio;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_send_post;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        initView();
        setRootOnTouchListener();
        setListenerToRootView();
    }

    /**
     * @param rootView
     * @return b
     * 判断键盘弹出状态
     */
    private boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }

    private void setRootOnTouchListener() {
        rlRoot.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard(activity);
                return false;
            }
        });
    }

    /**
     * 动态监听键盘状态
     */
    private void setListenerToRootView() {
        rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                keyboardShown = isKeyboardShown(rlRoot);
                if (flEmogi != null && llEmogi != null) {
                    if (keyboardShown) {
                        if (llEmogi.getVisibility() != View.VISIBLE || supportSoftInputHeight != getSupportSoftInputHeight()) {
                            ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);
                            isEmogiShow = false;
                            rlRoot.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            supportSoftInputHeight = getSupportSoftInputHeight();
                            flEmogi.getLayoutParams().height = supportSoftInputHeight;
                            flEmogi.requestLayout();
                            flEmogi.setVisibility(View.INVISIBLE);
                            llEmogi.setVisibility(View.VISIBLE);
                            linear2.setVisibility(View.GONE);
                            rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(this);
                        }
                    } else {
                        if (!isEmogiShow) {
                            flEmogi.setVisibility(View.INVISIBLE);
                            llEmogi.setVisibility(View.GONE);
                            linear2.setVisibility(View.VISIBLE);
                            ivEmogi.setImageResource(R.mipmap.chat_msg_emjoy);
                        }
                    }
                }
            }
        });
    }

    private int getSupportSoftInputHeight() {
        Rect r = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = this.getWindow().getDecorView().getRootView().getHeight();
        int softInputHeight = screenHeight - r.bottom;
        if (Build.VERSION.SDK_INT >= 26 && Build.VERSION.SDK_INT < 28) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight();
        }
        return softInputHeight;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideKeyboard(this);
        flEmogi.setVisibility(View.GONE);
        flVoice.setVisibility(View.GONE);
        llEmogi.setVisibility(View.GONE);
        linear2.setVisibility(View.VISIBLE);
        imageVoice.setImageResource(R.mipmap.send_post_unvoice);
        if (frameAnimatio != null) {
            frameAnimatio.stop();
            frameAnimatio.selectDrawable(2);
        }
    }

    private void hideKeyboard(Activity context) {
        if (context == null) return;
        final View v = context.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }


    private void showKeyboard(Activity context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);

    }

    private void initKeyBoard() {
        isEmogiShow = true;
        flEmogi.setVisibility(View.VISIBLE);
        if (emojiShowFragment == null) {
            emojiShowFragment = EmojiShowFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_emogi, EmojiShowFragment.newInstance()).commit();
        }
    }

    @Override
    public void onBackPressed() {
        if (isEmogiShow || isKeyboardShown(rlRoot)) {
            isEmogiShow = false;
            flEmogi.setVisibility(View.INVISIBLE);
            llEmogi.setVisibility(View.GONE);
            linear2.setVisibility(View.VISIBLE);
            hideKeyboard(this);
        } else {
            if (!TextUtils.isEmpty(etPostTitle.getText().toString().trim()) || !TextUtils.isEmpty(etPostContent.getText().toString().trim())
                    || !TextUtils.isEmpty(filePath) || (tlist != null && tlist.size() != 0)) {
                showCacheDialog();
            } else {
                finish();
            }
            // finish();
        }
    }

    /**
     * @return
     * @method
     * @description 退出
     * @date: 2018/11/1 19:37
     * @author: ljp
     */
    private void showCacheDialog() {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        //normalDialog.setTitle("我是一个普通Dialog");
        normalDialog.setMessage("确认退出发帖?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        DataCleanManager.clearAllCache(context);
                        dialog.dismiss();
                        try {
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * 数据实例化
     */
    private void initView() {
        etPostTitle.setFocusable(true);
        tlist = new ArrayList<>();
        circlePictureAdapter = new CirclePictureAdapter(context, tlist, R.layout.item_send_post_picture, 0);
        FullyGridLayoutManager fullyGridLayoutManager = new FullyGridLayoutManager(context, 3);
        fullyGridLayoutManager.setSmoothScrollbarEnabled(false);
        recyclerSendPictuer.setLayoutManager(fullyGridLayoutManager);
        recyclerSendPictuer.setAdapter(circlePictureAdapter);
        circlePictureAdapter.addFooterView(R.layout.item_send_post_picture);
        circlePictureAdapter.setAddClick(new CirclePictureAdapter.OnAddClick() {
            @Override
            public void setAddItemClick(int position) {
                initPicture();
            }

            @Override
            public void setRemoveItemClick(int position) {
                tlist.remove(position);
                circlePictureAdapter.refreshCurrentAdapter();
                if (circlePictureAdapter.getTlist().size() == 0) {
                    recyclerSendPictuer.setVisibility(View.GONE);
                }
            }

            @Override
            public void setSendImgBg(boolean flag) {
            }
        });
        ivEmogi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEmogiShow) {
                    isEmogiShow = false;
                    Log.i(TAG, "onClick: -etPostContent---" + etPostContent.hasFocus() + "--etPostTitle--" + etPostTitle.hasFocus());
                    if (etPostTitle.hasFocus()) {
                        showKeyboard(activity, etPostTitle);
                    } else if (etPostContent.hasFocus()) {
                        showKeyboard(activity, etPostContent);
                    }
                    // Log.i(TAG, "onClick: ---------"+editText.getId());
                    ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);
                    return;
                } else {
                    ivEmogi.setImageResource(R.mipmap.fabu_keyboard_icon);
                    initKeyBoard();
                    hideKeyboard(activity);
                }
            }
        });
        etPostContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* isEmogiShow = false;
                ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);*/

            }
        });
        etPostTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* isEmogiShow = false;
                ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);*/
            }
        });
        radioGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (radioVipRenew.isChecked()) {
                    radioVipRenew.setChecked(false);
                } else {
                    radioVipRenew.setChecked(true);
                }
            }
        });
        etPostTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    EmojiShowFragment.setEditMsg(etPostTitle);
                    Log.i(TAG, "onFocusChange: --etPostTitle--flEmogi-" + (flEmogi.getVisibility() == View.VISIBLE));
                    if (flEmogi.getVisibility() == View.VISIBLE) {
                        hideKeyboard(activity);
                        //etPostTitle.setInputType(InputType.TYPE_NULL);
                    }
                    isEmogiShow = false;
                    ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);
                }
            }
        });
        etPostContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    EmojiShowFragment.setEditMsg(etPostContent);
                    Log.i(TAG, "onFocusChange: -etPostContent---flEmogi---" + (flEmogi.getVisibility() == View.VISIBLE));
                    if (flEmogi.getVisibility() == View.VISIBLE) {
                        hideKeyboard(activity);
                        //etPostTitle.setInputType(InputType.TYPE_NULL);
                    }
                    isEmogiShow = false;
                    ivEmogi.setImageResource(R.mipmap.post_detail_emjoy);
                }
            }
        });

        etPostContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int lineHeight = etPostContent.getLineHeight();
                int location[] = new int[2];
                etPostContent.getLocationOnScreen(location);
                int x = location[0];

                // Log.i(TAG, "afterTextChanged: --etPostContent---getBottom----"+etPostContent.getBottom());
                // Log.i(TAG, "afterTextChanged: ---llEmogi--getTop----"+llEmogi.getTop());
                //Log.i(TAG, "afterTextChanged: ---etPostContent--locationY----"+location[1]);
                llEmogi.getLocationOnScreen(location);
                //s  Log.i(TAG, "afterTextChanged: ---llEmogi--getTop----"+llEmogi.getTop());

            }
        });


    }

    private CharSequence temp;

    @OnClick({R.id.linear_back, R.id.tv_post_send, R.id.linear_send_post_picture,
            R.id.linear_send_post_emjoy, R.id.linear_send_post_aite, R.id.linear_send_voice, R.id.linear_send_post_voice})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                if (isEmogiShow || isKeyboardShown(rlRoot)) {
                    isEmogiShow = false;
                    flEmogi.setVisibility(View.INVISIBLE);
                    llEmogi.setVisibility(View.GONE);
                    linear2.setVisibility(View.VISIBLE);
                    hideKeyboard(this);
                } else {
                    if (!TextUtils.isEmpty(etPostTitle.getText().toString().trim()) || !TextUtils.isEmpty(etPostContent.getText().toString().trim())
                            || !TextUtils.isEmpty(filePath) || (tlist != null && tlist.size() != 0)) {
                        showCacheDialog();
                    } else {
                        finish();
                    }
                }
                break;
            case R.id.tv_post_send://发送帖子，如果有照片，先上传照片
                setPictureList();
                break;
            case R.id.linear_send_post_picture://选择照片
                if (linearSendVoice.getVisibility() == View.GONE) {
                    initPicture();
                }
            case R.id.linear_send_post_emjoy:
                etPostTitle.setFocusable(true);
                etPostTitle.setFocusableInTouchMode(true);
                etPostTitle.requestFocus();//获取焦点 光标出现
                showKeyboard(activity, etPostTitle);
                break;
            case R.id.linear_send_post_aite://@好友
                Intent intent = new Intent(activity, MyFriendingListActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.linear_send_voice:
                imageSendVoiceIcon.setImageResource(0);
                imageSendVoiceIcon.setBackgroundResource(R.drawable.post_voice);
                frameAnimatio = (AnimationDrawable) imageSendVoiceIcon.getBackground();
                try {
                    player();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.linear_send_post_voice://p判断是否选择图片，选择照片不能录制语音
                if (recyclerSendPictuer.getVisibility() == View.GONE) {
                    recorder = new AudioRecorderUtil(FileUtil.getCacheFilePath("postVoice"));
                    if(Build.VERSION.SDK_INT < 23){
                        if(CheckAudioPermission.isHasPermission(context)){
                            setFragment(linearSendPostVoice, 0);
                        }else {
                            ActivityCompat.requestPermissions(this, new String[]{
                                    Manifest.permission.RECORD_AUDIO}, 1);
                        }
                    }else {
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                                != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(this, new String[]{
                                    Manifest.permission.RECORD_AUDIO}, 1);
                            Log.i(TAG, "onClick: -----if------");
                        } else {
                            setFragment(linearSendPostVoice, 0);
                            Log.i(TAG, "onClick: ----------else----------");
                        }
                    }
                }
                break;
        }
    }

    String title;//发帖标题
    String content;//发帖内容

    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果,再开启录制音频
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
             //setFragment(linearSendPostVoice, 0);
        } else {
            Toast.makeText(this, "用户拒绝了权限", Toast.LENGTH_SHORT).show();
        }
        //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * @return
     * @method
     * @description 判断是否有照片
     * @date: 2018/11/18 17:11
     * @author: ljp
     */
    private void setPictureList() {
        title = etPostTitle.getText().toString().trim();
        content = etPostContent.getText().toString().trim();
        if (TextUtils.isEmpty(title) && title.length() == 0) {
            toast_MakeText("请输入标题内容");
            return;
        }
        if (TextUtils.isEmpty(filePath)) {
            if (TextUtils.isEmpty(content) && content.length() == 0) {
                toast_MakeText("请输入帖子内容");
                return;
            }
        }
        tvPostSend.setEnabled(false);
        List<LocalMedia> tlist = circlePictureAdapter.getTlist();
        if (tlist != null && tlist.size() != 0) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < tlist.size(); i++) {
                LocalMedia localMedia = tlist.get(i);
                list.add(localMedia.getCompressPath());
            }
            setOssHttp(list);//有照片先上传照片
        } else if (!TextUtils.isEmpty(filePath)) {
            setOssVoice(filePath);
        } else {
            uploadHttp("", "", "");//没有照片，直接发帖
        }
    }

    /**
     * @return
     * @method
     * @description 上传录音到oss服务器
     * @date: 2018/9/25 15:54
     * @author: ljp
     */
    private void setOssVoice(String voice) {
        String name = "yinyin" + System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).
                        upload(name, voice, OssConfig.VOICE, new OssClient.OnUploadFile() {
                            @Override
                            public void onUploadFileSuccess(String info) {
                                uploadHttp("", Utils.spitString(info), String.valueOf(timeInterval));//发语音贴
                            }
                            @Override
                            public void onUploadFileFailed(String errCode) {
                            }
                        });
            }
        }).start();
    }
    /**
     * @return
     * @method
     * @description 上传照片到oss
     * @date: 2018/11/18 17:08
     * @author: ljp
     */
    private void setOssHttp(List<String> list) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OssClient.getInstance().init(context).
                            ossUploads(list, new OssClient.OnUploadFile() {
                                @Override
                                public void onUploadFileSuccess(String info) {
                                    //Log.i(TAG, "onUploadFileSuccess: -----" + info);
                                    uploadHttp(info, "", "");
                                }

                                @Override
                                public void onUploadFileFailed(String errCode) {
                                }
                            }, new StringBuffer());
                } catch (ClientException e) {
                    e.printStackTrace();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @return
     * @method
     * @description 发表帖子
     * @date: 2018/11/18 16:40
     * @author: ljp
     */
    private void uploadHttp(String path, String voiceUrl, String time) {
        String comment = radioVipRenew.isChecked() ? "2" : "1";
        MeInfoService.sendPost(mySeleInfo.getId(),
                SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context)
                , path, title, content, comment, voiceUrl, time).subscribe(result -> {
            Log.i(TAG, "uploadHttp: -----" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                toast_MakeText("发帖成功,审核中");
                Intent intent = new Intent(activity, MainActivity.class);
                intent.putExtra("flag", 0);
                startActivity(intent);
                finish();
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                tvPostSend.setEnabled(true);
                Utils.setToken(context);
            } else {
                tvPostSend.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            tvPostSend.setEnabled(true);
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "uploadHttp: ------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 选择照片
     * @date: 2018/11/18 16:56
     * @author: ljp
     */
    private void initPicture() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(9)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .compress(true)
                //.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .selectionMedia(tlist)// 是否传入已选图片 List<LocalMedia> list
                /*// .compressSavePath(getPath())//压缩图片保存地址
                 .freeStyleCropEnabled()// 裁剪框是否可拖拽 true or false
                 .openClickSound()// 是否开启点击声音 true or false

                 .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                 .cropCompressQuality()// 裁剪压缩质量 默认90 int*/
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // Log.i(TAG, "onActivityResult: -----" + selectList.size());
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // tlist.clear();
                    //tlist.addAll(selectList);
                    recyclerSendPictuer.setVisibility(View.VISIBLE);
                    circlePictureAdapter.setList(selectList);
                    circlePictureAdapter.refreshCurrentAdapter();
                    break;
                case 200://返回@数据
                    //data.getData()
                    //etPostContent
                    String name = data.getStringExtra("name");
                    Log.i(TAG, "onActivityResult: --------" + name);
                    etPostContent.insert(name);
                    break;
            }
        }
    }

    /**
     * @return
     * @method
     * @description 取消发送录音
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public void cacalSendVoice() {
        recorder.cancel();
    }

    /**
     * @return
     * @method
     * @description 开始录音
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public void startSendVoice() {
        String name = "yinyin" + System.currentTimeMillis() + ".aac";
        recorder.start(name);

    }

    private String filePath;//录音文件
    private long timeInterval;

    /**
     * @return
     * @method
     * @description 结束发送语音消息
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public void endSendVoice() {
        recorder.stop();
        if (recorder.getSumTime() / 1000 < 5) {
            Toast.makeText(this, getResources().getString(R.string.post_audio_too_short), Toast.LENGTH_SHORT).show();
        } else {
            flVoice.setVisibility(View.GONE);
            imageVoice.setImageResource(R.mipmap.send_post_unvoice);
            timeInterval = (long) Math.ceil(recorder.getSumTime() / 1000);//录音时长
            filePath = recorder.getFilePath();//录音地址
            //Log.i(TAG, "endSendVoice: ------getSumTime-----"+recorder.getSumTime());
            //Log.i(TAG, "endSendVoice: ------timeInterval-----"+timeInterval+"---filePath--"+filePath);
            linearSendVoice.setVisibility(View.VISIBLE);
            tvVoiceTime.setText(timeInterval + "s");
        }
    }
    /**
     * @return
     * @method
     * @description 监听录音状态
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public AudioRecorderUtil getRecorder() {
        return recorder;
    }

    private void setFragment(View view, int i) {
        if (flVoice.getVisibility() == View.VISIBLE) {
            flVoice.setVisibility(View.GONE);
            imageVoice.setImageResource(R.mipmap.send_post_unvoice);
        } else {
            setTabSelection(i);
            flVoice.setVisibility(View.VISIBLE);
            imageVoice.setImageResource(R.mipmap.send_post_voice);
        }
    }

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player() throws FileNotFoundException {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        if (mediaUtil == null) {
            mediaUtil = MediaUtil.getInstance();
            mediaUtil.play(new FileInputStream(filePath));
            frameAnimatio.start();
        } else {
            if (mediaUtil.setPlayer()) {
                mediaUtil.stop();
                frameAnimatio.stop();
                imageSendVoiceIcon.setBackgroundResource(0);
                imageSendVoiceIcon.setImageResource(R.mipmap.send_post_voice_icon3);
            } else {
                mediaUtil.play(new FileInputStream(filePath));
                imageSendVoiceIcon.setImageResource(0);
                imageSendVoiceIcon.setBackgroundResource(R.drawable.post_voice);
                frameAnimatio = (AnimationDrawable) imageSendVoiceIcon.getBackground();
                frameAnimatio.start();
            }
        }
        mediaUtil.setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                frameAnimatio.stop();
                imageSendVoiceIcon.setBackgroundResource(0);
                imageSendVoiceIcon.setImageResource(R.mipmap.send_post_voice_icon3);
            }
        });
    }

    @Override
    public void onAttachFragment(Fragment fragment) {//防止反复创建，造成重叠
        super.onAttachFragment(fragment);
        if (fragment instanceof SendPostVoiceFragment) {
            sendVoiceFragment = (SendPostVoiceFragment) fragment;
        }
    }

    /**
     * @return
     * @method
     * @description 隐藏fragment
     * @date: 2018/11/10 17:44
     * @author: ljp
     */
    @Override
    protected void hideFragments(FragmentTransaction transaction) {
        super.hideFragments(transaction);
        if (null != sendVoiceFragment) {
            transaction.hide(sendVoiceFragment);
        }
    }

    /**
     * @return
     * @method
     * @description 显示fragment
     * @date: 2018/11/10 17:44
     * @author: ljp
     */
    @Override
    protected void showFragment(FragmentTransaction transaction, int index) {
        super.showFragment(transaction, index);
        switch (index) {
            case 0:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{
                            Manifest.permission.RECORD_AUDIO}, 1);
                    Log.i(TAG, "onClick: -----if------");

                } else {
                    Log.i(TAG, "showFragment: --------------");
                    showFragmentTag = "IMChatSendVoiceFragment";
                    if (sendVoiceFragment == null) {
                        // 如果GogoFragment为空，则创建一个并添加到界面上
                        sendVoiceFragment = new SendPostVoiceFragment();
                        transaction.add(R.id.fl_voice, sendVoiceFragment, showFragmentTag);
                    } else {
                        if (sendVoiceFragment.isHidden()) {
                            transaction.show(sendVoiceFragment);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaUtil.getInstance().stop();
    }


}
